using AutoMapper;
using Finance.Api.Write.Applications.Commands.出库管理;
using Finance.Domain.盘点;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using Finance.Common;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Finance.Api.Write.Applications.CommandHands.出库管理
{
    public class OutAddCommandHandler : IRequestHandler<OutAddCommand, ApiResult<int>>
    {
        private readonly SqlsugarDb<OutBox> db;
        private readonly SqlsugarDb<OutDetail> dc;
        private readonly SqlsugarDb<ProductModel> productDb;
        private readonly SqlsugarDb<OutInModel> outInDb;
        private readonly IMapper mapper;
        private readonly ILogger<OutAddCommandHandler> _logger;

        public OutAddCommandHandler(SqlsugarDb<OutBox> db, IMapper mapper, SqlsugarDb<OutDetail> dc, SqlsugarDb<ProductModel> productDb, SqlsugarDb<OutInModel> outInDb, ILogger<OutAddCommandHandler> logger)
        {
            this.db = db;
            this.mapper = mapper;
            this.dc = dc;
            this.productDb = productDb;
            this.outInDb = outInDb;
            this._logger = logger;
        }

        public async Task<ApiResult<int>> Handle(OutAddCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            try
            {
                if (string.IsNullOrEmpty(request.OutNo))
                {
                    result.Code = Enumcode.Nonull;
                    result.message = "出库单号不能为空";
                    return result;
                }

                var addResult = mapper.Map<OutBox>(request);
                addResult.CreateTime = DateTime.Now;
                addResult.CreateName = "管理员"; 
                addResult.LoginId = 1; 
                addResult.IsDelete = false; 

             
                var detailEntity = new List<OutDetail>();
             
                
                foreach (var detail in request.DetailList)
                {
                    var outDetail = new OutDetail
                    {
                        ProductNo = detail.ProductNo,
                        ProductName = detail.ProductName,
                        ProductNum = detail.ProductNum,
                        DiffNum = detail.DiffNum,
                        OutNumber = detail.OutNumber,
                        checkid = request.checkid, 
                        IsDelete = false
                    };
                    detailEntity.Add(outDetail);
                    
                }

                var rows = await db.BeginTransaction(async () =>
                {
                    var EntityId = await db.AddReturnId(addResult);
                    if (EntityId == 0)
                    {
                        result.message = "添加失败";
                        result.data = 0;
                        result.Code = Enumcode.fail;
                        return 0;
                    }

                    foreach (var item in detailEntity)
                    {
                        item.Outid = EntityId;
                       
                    }
                    var detailReturn = await dc.Addlist(detailEntity);

                    // 更新产品库存数量
                    foreach (var detail in request.DetailList)
                    {
                        // 查找产品
                        var product = await productDb.FirstQuery().Where(p => p.ProductNo == detail.ProductNo && p.IsDelete == false).FirstAsync();
                        
                        if (product != null)
                        {
                            // 使用ProductStatusHelper更新产品信息
                            var updateResult = ProductStatusHelper.UpdateProductInfo(product, detail.DiffNum, false);
                            
                            if (!updateResult.IsSuccess)
                            {
                                throw new Exception($"产品 {detail.ProductName} 更新失败: {updateResult.Message}");
                            }
                            
                            await productDb.Updata(updateResult.UpdatedProduct);

                            // 添加出入库记录
                            var outInRecord = new OutInModel
                            {
                                OutInNo = request.OutNo,
                                OutInTime = request.OutTime,
                                OutInType = 1, // 1表示出库
                                LocationName = request.BoxName ?? product.Location,
                                GoinNumber = 0, // 入库数量为0
                                OutNumber = detail.DiffNum, // 出库数量
                                ProductNo = detail.ProductNo,
                                ProductName = detail.ProductName,
                                CreateTime = DateTime.Now,
                                CreateName = "管理员",
                                LoginId = 1,
                                IsDelete = false
                            };
                            await outInDb.AddAsync(outInRecord);
                        }
                    }

                    return detailReturn;
                });

                if (rows > 0)
                {
                    result.message = "盘亏出库成功";
                    result.data = 1;
                    result.Code = Enumcode.ok;
                }
                else
                {
                    result.message = "盘亏出库失败";
                    result.data = 0;
                    result.Code = Enumcode.fail;
                }
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.data = 0;
                result.Code = Enumcode.fail;
            }

            return await Task.FromResult(result);
        }
    }
} 